package com.ipet.item.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ipet.item.mapper.CategoryMapper;
import com.ipet.item.pojo.Category;
import com.ipet.item.service.CategoryService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
@Transactional
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {
    @Override
    public List<Map<String, Object>> findCategoryTree() {
        List<Category> categoryList = this.baseMapper.selectList(null);
        return findCategoryByPId(categoryList,0L);
    }

    @Override
    public List<Map<String, Object>> findCateGoryByNameTree(String name) {
        List<Category> categoryList = this.baseMapper.selectList(new QueryWrapper<Category>().like("name", name));
        return findCategoryByPId(categoryList , 0L);
    }

    private List<Map<String , Object>> findCategoryByPId(List<Category> categoryList , Long pid){
        List<Map<String , Object>> mapList = new ArrayList<>();
        for(Category category : categoryList){
            if(category.getParentId().equals(pid)){
                Map<String , Object> map = new HashMap<>();
                map.put("id" , category.getId());
                map.put("name",category.getName());
                map.put("sort",category.getSort());
                map.put("children" , findCategoryByPId(categoryList , category.getId()));
                mapList.add(map);
            }
        }
        Collections.sort(mapList, (Comparator<Map<String, Object>>) (o1, o2) -> (Integer) o1.get("sort") - (Integer) o2.get("sort"));
        return mapList;
    }
}
